//
//  QSMeauControllerLabel.swift
//  TestSwift
//
//  Created by Song on 2019/2/25.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit

class QSMeauControllerLabel: UILabel {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupLabelLongPressGes()
        self.setupLabelTapGes()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 必须重写这个方法
    override var canBecomeFirstResponder: Bool {
        get {
            return true
        }
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(qs_delete){
            return true
        }
        return false
    }
    
    // MARK: - 方法
    private func setupLabelTapGes() {
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapGest))
        
        self.addGestureRecognizer(tap)
    }
    
    /// 创建长按手势
    private func setupLabelLongPressGes() {
        let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(labelLongPressAction))
        // 长按手势最小触发时间
        longPressGes.minimumPressDuration = 1
        
        self.addGestureRecognizer(longPressGes)
    }
    
    /// 长按方法
    @objc private func labelLongPressAction(){
        // 如果 Menu 已经被创建那就不再重复创建 menu
        if (UIMenuController.shared.isMenuVisible){
            return
        }
        
        // 要成为第一响应者否则某些功能会错乱
        self.becomeFirstResponder()
        
        let menu = UIMenuController.shared
        
        // 设置 Menu 所显示的 items和对应调用的方法
        menu.menuItems = [UIMenuItem(title: "删除", action: #selector(qs_delete))]
        
        // 设置箭头方向
        menu.arrowDirection = .default
        
        var width: CGFloat = 0.0
        let textWidth = (self.text ?? "").qs_obtainWidthWith(font: self.font, height: 30.0)
        if textWidth < self.qs_width {
            width = textWidth
        } else {
            width = self.qs_width
        }
        
        // 设置添加上 menu 的目标控件的 rect 和目标控件
        menu.setTargetRect(CGRect.init(x: 0.0, y: 0.0, width: width, height: self.qs_height), in: self)
        // 令 Menu 可见
        menu.setMenuVisible(true, animated: true)
    }
    
    /// 单击方法
    @objc private func tapGest() {
        if self.tapAction != nil {
            self.tapAction!()
        }
    }
    
    @objc func qs_delete() {
        if self.deleteAction != nil {
            self.deleteAction!()
        }
    }
    
    // MARK: - 属性
    var deleteAction: (() -> ())?
    // 点击触发
    var tapAction: (() -> ())?
}
